package com.ict.txmsv2.utils;

import com.ict.txmsv2.exception.BadFileTypeException;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Author lht
 * @date 2021/9/24 - 22:36
 * @description: word文档工具类
 */
public class WordDocUtils {

    private static int cnt = 1;
    /**
     * 文件扩展名
     */
    private static final String DOC_TYPE1 = "doc";
    private static final String DOC_TYPE2 = "docx";
    /**
     * 一共9张表
     */
    private static final int TABLE_NUM = 9;

    public static List<Queue<String>> handleWordInfo2List(MultipartFile file) throws IOException,BadFileTypeException {
        String filename = file.getOriginalFilename();
        String extensionName = FileUtil.getExtensionName(filename);
        if (!DOC_TYPE1.equals(extensionName) && !DOC_TYPE2.equals(extensionName)) {
            throw new BadFileTypeException("文件类型错误");
        }
        InputStream inputStream = file.getInputStream();
        POIFSFileSystem pfs = new POIFSFileSystem(inputStream);
        HWPFDocument hwpfDocument = new HWPFDocument(pfs);
        Range range = hwpfDocument.getRange();
        TableIterator it = new TableIterator(range);
        List<Queue<String>> list = new ArrayList<>(TABLE_NUM);
        for (int i = 0; i < TABLE_NUM; i++) {
            list.add(new LinkedList<>());
        }
        while (it.hasNext()) {
            Table tb = it.next();
            if (cnt == 10) {
                break;
            }
            Queue<String> q = list.get(cnt++ - 1);
            // 迭代行，默认从0开始
            for (int i = 1; i < tb.numRows(); i++) {
                TableRow tr = tb.getRow(i);
                // 迭代列，默认从0开始
                for (int j = 1; j < tr.numCells(); j++) {
                    // 取得单元格
                    TableCell td = tr.getCell(j);
                    // 取得单元格的内容
                    String s = "";
                    int count = td.numParagraphs();
                    for (int k = 0; k < count; k++) {
                        // 获取第k个段落
                        Paragraph para = td.getParagraph(k);
                        s += para.text().trim();
                        if (count > 1 && k != count - 1) {
                            s += ",";
                        }
                    }
                    if (!"".equals(s)) {
                        q.add(s);
                    }
                }
            }
        }
        return list;
    }
}
